const domObserver = chrome.runtime.getURL('lib/DOMobserver.js');
const myAxios = chrome.runtime.getURL('lib/axios.min.js');
import axios from './lib/axios.min.js';
import { getAccessParams } from './lib/common.js';
import { getAuthAxios } from './lib/authAxios.js';
// pdf 转换
const pdfminjs = chrome.runtime.getURL('lib/pdf.min.js');
const pdfworkerjs = chrome.runtime.getURL('lib/pdf.worker.min.js');
const dayjs = chrome.runtime.getURL('lib/dayjs.min.js');
const TARGET_DOMAINS = ['sdyx2.sd.sgcc.com.cn', 'localhost', 'c.com'];
const SCRIPT_BASE_URL = 'http://192.168.161.52:18090/api/repair/v1/repair-dict/getScript';

// 域名匹配（支持端口）
function isTargetDomain(hostname) {
  const cleanHost = hostname.split(':')[0]; // 去除端口
  return TARGET_DOMAINS.some(domain => cleanHost === domain || cleanHost.endsWith(`.${domain}`));
}

// 获取远程脚本
async function safeFetch(url) {
  const response = await fetch(url);
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.text();
}
// 添加消息监听
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'getChromeObject') {
    // 返回需要共享的chrome对象属性或方法
    sendResponse({
      status: 'success',
      data: {
        runtime: chrome.runtime,
        storage: chrome.storage
        // 可根据需要添加其他chrome API
      }
    });
  }
  return true; // 保持消息通道开放
});

// 主监听逻辑
chrome.webNavigation.onCompleted.addListener(
  async details => {
    const url = new URL(details.url);
    let scriptCode = '';
    let key = '3a7d4e2f8c0b1a9d6e5f7c3b2a1d0e9f'; // id 自我生成
    const authAxios = getAuthAxios();
    const res = await authAxios.post('http://10.158.212.196:34002/yxjc/api/yxjc/v1/yxjcScript/list', { scriptKey: key });
    scriptCode = res.data && res.data.data && res.data.data.list[0].scriptContent;
    if (!scriptCode) return;
    if (isTargetDomain(url.hostname)) {
      try {
        //const scriptUrl = `${SCRIPT_BASE_URL}?domain=${encodeURIComponent(url.hostname)}`;
        //const scriptCode = await safeFetch(scriptUrl);
        // 这里是要注入到目标页面的脚本代码
        // 支持同时加载多个 scriptUrl，优先注入 globalVar.js
        await chrome.scripting.executeScript({
          target: { tabId: details.tabId },
          files: ['lib/globalVar.js'],
          world: 'MAIN'
        });
        //注入方法html
        await chrome.scripting.executeScript({
          target: { tabId: details.tabId },
          func: (domObserver, scriptCode, myAxios, pdfminjs, pdfworkerjs,dayjs) => {
            // 2. 加载 axios
            const loadAxios = () => {
              return new Promise(resolve => {
                const script = document.createElement('script');
                script.src = myAxios;
                script.onload = () => {
                  console.log('axios 加载完成');
                  resolve();
                };
                script.onerror = e => console.error('axios 加载失败', e);
                document.head.appendChild(script);
              });
            };

            // 3. 加载 DOMObserver
            const loadObserver = () => {
              return new Promise(resolve => {
                const script = document.createElement('script');
                script.src = domObserver;
                script.onload = () => {
                  console.log('DOMObserver 加载完成');
                  resolve();
                };
                script.onerror = e => console.error('DOMObserver 加载失败', e);
                document.head.appendChild(script);
              });
            };
            const pdfminjsLoad = () => {
              return new Promise(resolve => {
                const script = document.createElement('script');
                script.src = pdfminjs;
                script.onload = () => {
                  console.log('pdfminjs 加载完成');
                  resolve();
                };
                script.onerror = e => console.error('pdfminjs 加载失败', e);
                document.head.appendChild(script);
              });
            };
            const pdfworkerminjsLoad = () => {
              return new Promise(resolve => {
                const script = document.createElement('script');
                script.src = pdfworkerjs;
                script.onload = () => {
                  console.log('pdfworkerminjsLoad 加载完成');
                  resolve();
                };
                script.onerror = e => console.error('pdfworkerminjsLoad 加载失败', e);
                document.head.appendChild(script);
              });
            };
            const loadDayJS = () => {
              return new Promise(resolve => {
                const script = document.createElement('script');
                script.src = dayjs;
                script.onload = () => {
                  console.log('dayjs 加载完成');
                  resolve();
                };
                script.onerror = e => console.error('dayjs加载失败', e);
                document.head.appendChild(script);
              });
            };
            // 4. 并行加载 + 确保顺序执行
            Promise.all([loadAxios(), loadObserver(), pdfminjsLoad(), pdfworkerminjsLoad(),loadDayJS()]).then(() => {
              // 5. 依次注入所有业务代码（globalVar.js 必须第一个注入）
              const script = document.createElement('script');
              script.textContent = scriptCode;
              document.head.appendChild(script);
              script.remove();
            });
          },
          args: [domObserver, scriptCode, myAxios, pdfminjs, pdfworkerjs,dayjs],
          world: 'MAIN' // 使用 MAIN 确保能访问页面变量
        });
      } catch (error) {
        console.error(`[失败] ${url.hostname} 错误:`, error);
      }
    }
  },
  {
    url: [{ hostSuffix: 'sdyx2.sd.sgcc.com.cn' }, { hostSuffix: 'localhost' }, { hostSuffix: 'c.com' }]
  }
);
